<template>
  <el-main class="bg edit_wrap answer_edit_wrap">
    <el-form ref="formRules" :model="form" status-icon label-width="70px">
      <el-row class="row_e">
        <el-col v-if="if_answered" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <div class="title_margin" style="margin-bottom: 20px" v-if="score_state === 0">
            未评分
          </div>
          <div class="title_margin" style="margin-bottom: 20px" v-else>
            已评分，得分：<span style="color: red">{{
              answer_form.score
            }}</span>
          </div>
        </el-col>
        <el-col v-for="(o, i) in question_list" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <div class="title_margin" v-if="o.type === '单选题'">
            {{
              o.question_order +
              ".单选题：" +
              o.title +
              " (" +
              o.score +
              "分)"
            }}
            <span v-if="if_answered" class="score_show">--------{{ answer_scores[i] }}分</span>
          </div>
          <div class="title_margin" v-else-if="o.type === '多选题'">
            {{
              o.question_order +
              ".多选题：" +
              o.title +
              " (" +
              o.score +
              "分)"
            }}
            <span v-if="if_answered" class="score_show">--------{{ answer_scores[i] }}分</span>
          </div>
          <div class="title_margin" v-else-if="o.type === '判断题'">
            {{
              o.question_order +
              ".判断题：" +
              o.title +
              " (" +
              o.score +
              "分)"
            }}
            <span v-if="if_answered" class="score_show">--------{{ answer_scores[i] }}分</span>
          </div>
          <div class="title_margin" v-else-if="o.type === '填空题'">
            {{
              o.question_order +
              ".填空题：" +
              o.title +
              " (" +
              o.score +
              "分)"
            }}
            <span v-if="if_answered" class="score_show">
              <span v-if="score_state === 0">--------未评分</span>
              <span v-else>--------{{ answer_scores[i] }}分</span>
            </span>
          </div>
          <div class="title_margin" v-else>
            {{
              o.question_order +
              ".主观题：" +
              o.title +
              " (" +
              o.score +
              "分)"
            }}
            <span v-if="if_answered" class="score_show">
              <span v-if="score_state === 0">--------未评分</span>
              <span v-else>--------{{ answer_scores[i] }}分</span>
            </span>
          </div>
          <el-form-item v-if="o.type === '单选题'" label="">
            <el-radio :disabled="if_answered" v-for="(q, k) in get_question_list(o.question_item)" v-model="answers[i]"
              :key='k' :label="q">{{ q }}</el-radio>
            <div class="score_show" v-if="if_answered && referenceanswers[i]">
              参考答案：{{ referenceanswers[i] }}
            </div>
          </el-form-item>
          <el-form-item v-else-if="o.type === '多选题'" label="">
            <el-checkbox-group :disabled="if_answered" v-model="answers[i]">
              <el-checkbox v-for="(q, v) in get_question_list(o.question_item)" :label="q" :key='v'></el-checkbox>
            </el-checkbox-group>
            <div class="score_show" v-if="if_answered && referenceanswers[i]">
              参考答案：{{ referenceanswers[i] }}
            </div>
          </el-form-item>
          <el-form-item v-else-if="o.type === '判断题'" label="">
            <el-radio :disabled="if_answered" v-for="(q, o) in get_question_list(o.question_item)" v-model="answers[i]"
              :key='o' :label="q">{{ q }}</el-radio>
            <div class="score_show" v-if="if_answered && referenceanswers[i]">
              参考答案：{{ referenceanswers[i] }}
            </div>
          </el-form-item>
          <el-form-item v-else-if="o.type === '填空题'" label="">
            <el-input :disabled="if_answered" style="width: 500px" v-model="answers[i]"></el-input>
            <div class="score_show" v-if="if_answered">
              参考答案：{{ referenceanswers[i] }}
            </div>
          </el-form-item>
          <el-form-item v-else label="">
            <el-input :disabled="if_answered" type="textarea" v-model="answers[i]">
            </el-input>
            <div class="score_show" v-if="if_answered">
              参考答案：{{ referenceanswers[i] }}
            </div>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="提交人">
            <el-input disabled="" v-model="submit_user_str"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="footer">
        <el-button type="primary" v-if="!if_answered" @click="submit_main()" size="large">提交</el-button>
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
    <div v-if="!if_answered" class="countdown">
      距离考试结束还有：<span>{{ countdownTxt }}</span>
    </div>
  </el-main>
</template>
<script setup>
import { ref, onMounted, onUnmounted, reactive } from "vue";
import { $post, $get } from "@/api/Api.js";
import { $getUrlParams, $check_exam } from "@/utils/utils.js";
import storageHelper from "@/libs/StorageHelper";
import { useRouter } from "vue-router";
let router = useRouter();
let UserInfo = storageHelper.getUserInfo();
let user_id = storageHelper.getUserInfo().user_id;
const exam_id = $getUrlParams().exam_id;
let field = ref("exam_id");
let url_set = ref("/api/subject_user_answer/set?");
let url_get_obj = ref("/api/user_answer/get_obj");
let url_upload = ref("/api/user_answer/upload");
let url_add = ref("/api/user_answer/add");
let url_add_user_answer_wrong = ref("/api/user_answer_wrong/add");
let url_get_question_list = ref("/api/exam_question/get_list");
let url_get_exam_question = ref("/api/exam_question/get_obj");
let query = ref({ exam_id: exam_id });
let form = ref({
  exam_id: 0,
  name: "",
  duration: 60,
  score: 0,
  status: "启用",
});

let question_list = ref([]);
let answers = ref([]);
let submit_user_str = ref("");
let answer_form = ref({
  user_answer_id: 0,
  user_id: 0,
  exam_id: 0,
  score: 0,
  score_state: 0,
  answers: [],
  score_detail: [],
  objective_score: 0,
  subjective_score: 0,
  nickname: "",
});
let if_answered = ref(false);
let countdownTxt = ref("");
let countdownTime = ref(null);
let score_state = ref(0);
let answer_scores = ref([]);
let referenceanswers = ref([]);
let formRules = ref(null);
//  倒计时
let countdownFun = (diffTime) => {
  if (diffTime > 0) {
    countdownTime.value = setInterval(() => {
      let diffM =
        Math.floor(diffTime / 60) > 9
          ? Math.floor(diffTime / 60)
          : `0${Math.floor(diffTime / 60)}`;
      let diffS =
        Math.floor(diffTime % 60) > 9
          ? Math.floor(diffTime % 60)
          : `0${Math.floor(diffTime % 60)}`;
      countdownTxt.value = `${diffM}分${diffS}秒`;
      diffTime--;
      if (diffTime < 0) {
        alert("时间到，结束!");
        clearInterval(countdownTime.value);
        submit_main();
        return
      }
    }, 1000);
  }
}
let get_obj_exam = async () => {
  let Json = await $get("/api/exam/get_obj?exam_id=" + exam_id);
  if (Json.result) {
    form.value = Json.result.obj
     if (!if_answered.value) {
        const remainingTime = 60 * form.value.duration; // 初始化剩余时间为60分钟
        countdownFun(remainingTime);
      }
  }
}
let get_obj_after = async () => {
  
  let userJson = await $get("/api/user/get_obj?user_id=" + UserInfo.user_id);
  if (userJson.result) {
    submit_user_str.value = userJson.result.obj.username + "-" + userJson.result.obj.nickname;
    answer_form.value.user_id = userJson.result.obj.user_id;
    answer_form.value.nickname = userJson.result.obj.nickname;
  } else if (userJson.error) {
    console.error(userJson.error);
  }
  let json = await $get(
    url_get_question_list.value +
    "?exam_id=" +
    exam_id +
    "&orderby=question_order"
  );
  if (json.result && json.result.count) {
    question_list.value = json.result.list;
    for (let i = 0; i < question_list.value.length; i++) {
      if (question_list.value[i].type === "多选题") {
        answers.value[i] = [];
      } else {
        answers.value[i] = "";
      }
    }
  } else if (json.error) {
    console.error(json.error);
  }
  let answerJson = await $get(
    "/api/user_answer/get_obj?user_id=" +
    answer_form.value.user_id +
    "&exam_id=" +
    exam_id
  );
  if (answerJson.result && answerJson.result.obj != null && answers.value.length) {
    answer_form.value = answerJson.result.obj;
    score_state.value = answerJson.result.obj.score_state;
    answer_form.value.answers = JSON.parse(answer_form.value.answers);
    answer_form.value.score_detail = JSON.parse(answer_form.value.score_detail);
    for (let i = 0; i < answer_form.value.answers.length; i++) {
      answers.value[i] = answer_form.value.answers[i].answer;
      answer_scores.value[i] = answer_form.value.score_detail[i].score;
      if (
        question_list.value[i].type === "单选题" ||
        question_list.value[i].type === "判断题" ||
        question_list.value[i].type === "多选题"
      ) {
        if (answer_scores.value[i] !== question_list.value[i].score) {
          referenceanswers.value[i] = question_list.value[i].answer;
        }
      } else {
        referenceanswers.value[i] = question_list.value[i].answer;
      }
    }
    if_answered.value = true;
  } else if (answerJson.error) {
    console.error(answerJson.error);
  }
  console.log(!if_answered.value)
 
};
let get_question_list = (question_str) => {
  let question_list = question_str.split("\n");
  return question_list;
};
let submit_main = () => {
  console.log(countdownTxt.value)
  // if (countdownTxt.value == '00分00秒') {
  //   ElMessage.error('已超时，不能提交试卷');
  //   return
  // }
  answer_form.value.exam_id = exam_id;
  for (let i = 0; i < answers.value.length; i++) {
    let obj = {
      exam_question_id: question_list.value[i].exam_question_id,
      answer: answers.value[i],
    };
    console.log(question_list.value);
    answer_form.value.answers[i] = obj;
    if (
      question_list.value[i].type === "单选题" ||
      question_list.value[i].type === "判断题"
    ) {
      if (answers.value[i] === question_list.value[i].answer) {
        let obj = {
          exam_question_id: question_list.value[i].exam_question_id,
          score: question_list.value[i].score,
        };
        answer_form.value.score_detail[i] = obj;
        answer_form.value.objective_score =
          answer_form.value.objective_score + question_list.value[i].score;
      } else {
        let obj = {
          exam_question_id: question_list.value[i].exam_question_id,
          score: 0,
        };
        answer_form.value.score_detail[i] = obj;
      }
    } else if (question_list.value[i].type === "多选题") {
      let flag = true;
      let question_answer_list = question_list.value[i].answer.split("|");
      if (answers.value[i].length !== question_answer_list.length) {
        flag = false;
      } else {
        for (let j = 0; j < question_answer_list.length; j++) {
          if (answers.value[i].indexOf(question_answer_list[j]) === -1) {
            flag = false;
            break;
          }
        }
      }
      if (flag) {
        let obj = {
          exam_question_id: question_list.value[i].exam_question_id,
          score: question_list.value[i].score,
        };
        answer_form.value.score_detail[i] = obj;
        answer_form.value.objective_score =
          parseFloat(answer_form.value.objective_score) +
          parseFloat(question_list.value[i].score);
      } else {
        let obj = { exam_question_id: question_list.value[i].exam_question_id, score: 0 };
        answer_form.value.score_detail[i] = obj;
      }
    } else {
      let obj = { exam_question_id: question_list.value[i].exam_question_id, score: 0 };
      answer_form.value.score_detail[i] = obj;
    }
  }
  answer_form.value.answers = JSON.stringify(answer_form.value.answers);
  answer_form.value.score_detail = JSON.stringify(
    answer_form.value.score_detail
  );
  answer_form.value.score =
    parseFloat(answer_form.value.subjective_score) +
    parseFloat(answer_form.value.objective_score);
  //提交错题记录
  post_user_answer_wrong();
  let url = url_add.value;
  $post(url, answer_form.value).then((json, status) => {
    console.log("提交结果：", json);
    if (json.result) {
      submit_after();
      //events("submit_after", json, null);
    } else if (json.error) {
      ElMessage.error(json.error.message);
    }
  });
};

//根据问题ID从json列表中取出答案对象
let get_answer_wrong_by_id = (jsonList, exam_question_id) => {
  let list = JSON.parse(jsonList);
  for (let i = 0; i < list.length; i++) {
    let answer = list[i];
    if (answer.exam_question_id == exam_question_id) {
      console.log(answer);
      return answer;
    }
  }
  return null;
};
//提交错题记录，把user_answer表中的answers字段json解析出来，转存到user_answer_wrong表中
let post_user_answer_wrong = async () => {
  for (let i = 0; i < question_list.value.length; i++) {
    let exam_question = question_list.value[i];
    if (exam_question.exam_question_id) {
      let json = await $get(
        url_get_exam_question.value +
        "?exam_question_id=" +
        exam_question.exam_question_id
      );

      if (json.result) {
        let obj = get_answer_wrong_by_id(
          answer_form.value.answers,
          exam_question.exam_question_id
        );

        let questionObj = json.result.obj;

        //填空题和主观题不列入错记录
        if (questionObj.type == "填空题" || questionObj.type == "主观题") {
          continue;
        }
        let answer_wrong_form = {
          subject_name: questionObj.subject_name,
          type: questionObj.type,
          title: questionObj.title,
          question_item: questionObj.question_item,
          answers: JSON.stringify(obj.answer),
          answer: questionObj.answer.length > 0 ? questionObj.answer : "",
          nickname: answer_form.value.nickname,
          user_id: user_id,
        };

        let submitAnswer = obj.answer;
        if (questionObj.type == "多选题") {
          submitAnswer = obj.answer.join("|");
        }

        if (exam_question.answer.toString() != submitAnswer) {
          $post(url_add_user_answer_wrong.value, answer_wrong_form).then(
            (json, status) => {
              console.log("提交错题结果：", json);
            }
          );
        }
      }
    }
  }
};
let submit_after = () => {
  ElMessage.success("提交成功！");
  router.push("./table");
};
let cancel = () => {
  router.go(-1);
  // router.push("./table");
};

onMounted(() => {
  get_obj_exam()
  // if(form.value.user_id){
  get_obj_after();

  // }
  // $('#exam_view').myPlugin()
});
onUnmounted(() => {
  clearInterval(countdownTime.value);
});
</script>

<style lang="less" scoped>
.edit_wrap {
  position: relative;

  .title_margin {
    margin-left: 70px;
  }

  .countdown {
    position: absolute;
    right: 20px;
    top: 20px;
  }

  .countdown span {
    color: red;
  }

  .score_show {
    margin-left: 20px;
    color: red;
  }

  .footer {
    text-align: right;
  }
}
</style>
